export default {
    convertToFlat2(data, parentId = null, delchildren = false) {
        return data.reduce((acc, curr) => {
            let o = { ...curr, parentId };
            if (delchildren) delete o.children;
            acc.push(o);
            if (curr.children) {
                acc = acc.concat(convertToFlat(curr.children, curr.id, delchildren));
            }
            return acc;
        }, []);
    },
    convertLevel2ParentId: function convertLevel2ParentId(data, levelField, parentIdField = 'parentId') {
        levelField = levelField || "Code";
        let levelGroupBy = _.groupBy(data, item => _.size(item[levelField]));
        let levelKeys = _.keys(levelGroupBy);
        let prevVal = 0;
        let levelLength = (prevVal = 0, _.transform(levelKeys, (result, value) => {
            result[value] = value - prevVal, prevVal = value
        }, {}));


        _.each(levelGroupBy, (val, key) => {
            let substrLen = key - levelLength[key];
            _.map(val, item => { item[parentIdField] = item[levelField].substring(0, substrLen) })
        })

        let values = _.values(levelGroupBy);

        let returnValue =  _.flatten(values);

        return returnValue;

        // // bbb = (p=0,_.transform(['2', '5', '8', '11'],(r,v)=>{r[v]=v-p,p=v},{}))
        // _.flatten(_.values(_.each(fff, (val, k) => { bbb[k], _.map(val, item => { item.pid = item.Code.substring(bbb[k]) }) })))
    },
    convertLevel2ParentIdChatGPT:function convertLevel2ParentIdChatGPT(data, levelField, parentIdField = 'parentId') {
        debugger;
        return _.chain(data)
          .groupBy(item => item[levelField].length)
          .mapValues((val, key) => _.map(val, item => ({ ...item, [parentIdField]: item[levelField].substring(0, key) })))
          .flatten()
          .value();
      },

    convertToFlat: function convertToFlat(data, parentId = null, opts) {
        opts = Object.assign({ pidName: 'parentId', omitChildren: false, childrenName: 'children' }, opts);
        var { omitChildren, childrenName, pidName } = opts;
        return data.reduce((acc, curr) => {
            var o = { ...curr };
            o[pidName] = parentId;
            if (omitChildren) delete o[childrenName];
            acc.push(o);
            if (curr[childrenName]) {
                acc = acc.concat(convertToFlat(curr[childrenName], curr.id, opts));
            }
            return acc;
        }, []);
    }
}
